﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PlasmaMes.Services
{
    class TcpService
    {
        private static TcpService instance;
        private static readonly object locker = new object();

        private TcpService() { }

        public static TcpService Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        instance = new TcpService();
                    }
                }

                return instance;
            }
        }

        //上游机台
        public TcpClient tcpClient;
        public NetworkStream tcpstream = null;
        public volatile string tcpResponse;//tcp回应的消息
        public bool istcpListen = false;//监听tcp的任务标志位
        public bool istcpConnected = false;


        //下游机台
        public TcpClient d_tcpClient;
        public NetworkStream d_tcpstream = null;
        public volatile string d_tcpResponse;//tcp回应的消息
        public bool d_istcpListen = false;//监听tcp的任务标志位
        public bool d_istcpConnected = false;


        public bool Tcp_Connected(string ip, int port)
        {
            if (istcpConnected)
            {
                MessageBox.Show("已存在连接，请勿重复链接");
                return false;
            }
            else
            {
                if (tcpClient == null)
                {
                    tcpClient = new TcpClient();
                }

                try
                {
                    tcpClient.Connect(ip, port);

                    tcpstream = tcpClient.GetStream();

                    istcpConnected = true;

                    ListenTcpMsg();

                    LogService.Instance.LogInfo("与上游机台通讯成功");

                    return true;
                }
                catch (Exception ex)
                {
                    LogService.Instance.LogError("上游机台Tcp连接失败，请检查");
                    LogService.Instance.LogError($"{ex}");
                    return false;
                }
            }
        }

        public bool Tcp_DisConnected()
        {
            try
            {
                if (istcpConnected)
                {
                    if(tcpClient != null)
                    {
                        tcpClient.Close();
                        tcpClient = null;
                        LogService.Instance.LogError("已断开与上游机台的连接");
                    }
                    if (tcpstream != null)
                    {
                        tcpstream.Close();
                        tcpstream = null;
                    }

                    istcpConnected = false;
                    return true;
                }
                else
                {
                    LogService.Instance.LogError("上游Tcp还没建立连接");
                    MessageBox.Show("上游Tcp还没建立连接");
                    return false;
                }
            }
            catch(Exception ex)
            {
                LogService.Instance.LogError(ex.ToString());
                return false;
            }
          
        }

        /// <summary>
        /// 发消息给软件
        /// </summary>
        /// <param name="message"></param>
        public async Task<string> Tcp_SemdMsg(string message)
        {
            if (tcpstream != null)
            {
                byte[] msg = Encoding.ASCII.GetBytes(message);

                // 清空旧响应（关键）
                tcpResponse = string.Empty;

                //tcpstream.Write(msg, 0, msg.Length);
                await tcpstream.WriteAsync(msg, 0, msg.Length);
                tcpstream.Flush();

                var sw = new Stopwatch();
                sw.Start();
                while (string.IsNullOrEmpty(tcpResponse) && sw.ElapsedMilliseconds < 5000)
                {
                    await Task.Delay(10);
                }
                sw.Stop();

                if (string.IsNullOrEmpty(tcpResponse))
                {
                    LogService.Instance.LogError("等待响应超时");

                }

                return tcpResponse.Trim(); // 返回响应（去掉空格或换行）

            }
            else
            {
                return "";

            }

        }


        public async Task<string> ReadFormPLC(string readCommand)
        {
            try
            {
                // 发送指令并等待响应
                string response = await Instance.Tcp_SemdMsg(readCommand);

                // 判断是否是有效数据（不是 OK）
                if (response.Equals("OK", StringComparison.OrdinalIgnoreCase))
                {
                    MessageBox.Show("收到 'OK'，可能是上一次写入上游机台基恩士PLC的响应，请稍后再试。");
                    return "";
                }

                // 正常显示读取结果

                return response;

            }
            catch (TimeoutException)
            {
                LogService.Instance.LogError("读取超时，未收到上游机台基恩士PLC响应。");
                return "超时";
            }
            catch (Exception ex)
            {
                LogService.Instance.LogError("读取上游机台基恩士PLC失败: " + ex.Message);
                return "错误: " + ex.Message;
            }
        }


        public void ListenTcpMsg()
        {
            if (istcpListen)
            {
                MessageBox.Show("监听上游机台任务已在运行");
            }
            {
                Task.Factory.StartNew(() =>
                {
                    istcpListen = true;
                    byte[] buffer = new byte[1024];
                    while (istcpListen)
                    {
                        if (tcpstream.DataAvailable)
                        {
                            Array.Clear(buffer, 0, buffer.Length);
                            int bytelength = tcpstream.Read(buffer, 0, buffer.Length);
                            if (bytelength > 0)
                            {
                                tcpResponse = string.Empty;
                                tcpResponse = Encoding.ASCII.GetString(buffer, 0, bytelength);
                                string clean = tcpResponse.Trim();

                                // 忽略空响应或纯回车
                                if (!string.IsNullOrWhiteSpace(clean) && !clean.Equals("OK", StringComparison.OrdinalIgnoreCase))
                                {
                                    tcpResponse = clean; // 只有有效读数才赋值
                                }
                                else if (clean.Equals("OK", StringComparison.OrdinalIgnoreCase))
                                {
                                    // 可选：记录日志，但不覆盖 tcpResponse
                                    // tcpResponse 不更新，避免干扰读取
                                }

                            }

                        }

                        Thread.Sleep(10);
                    }

                    LogService.Instance.LogWarning("断开上游机台的监听");
                    istcpListen = false;

                });
            }
        }




        public bool D_Tcp_Connected(string ip, int port)
        {
            if (d_istcpConnected)
            {
                MessageBox.Show("已存在连接，请勿重复链接");
                return false;
            }
            else
            {
                if (d_tcpClient == null)
                {
                    d_tcpClient = new TcpClient();
                }

                try
                {
                    d_tcpClient.Connect(ip, port);

                    d_tcpstream = d_tcpClient.GetStream();

                    d_istcpConnected = true;

                    D_ListenTcpMsg();

                    LogService.Instance.LogInfo("与下游机台通讯成功");

                    return true;
                }
                catch (Exception ex)
                {
                    LogService.Instance.LogError("下游机台Tcp连接失败，请检查");
                    LogService.Instance.LogError($"{ex}");
                    return false;
                }
            }
        }


        public bool D_Tcp_DisConnected()
        {
            try
            {
                if (d_istcpConnected)
                {
                    if (d_tcpClient != null)
                    {
                        d_tcpClient.Close();
                        d_tcpClient = null;
                        LogService.Instance.LogError("已断开与下游机台的连接");
                    }
                    if (d_tcpstream != null)
                    {
                        d_tcpstream.Close();
                        d_tcpstream = null;
                    }

                    d_istcpConnected = false;
                    return true;
                }
                else
                {
                    LogService.Instance.LogError("下游Tcp还没建立连接");
                    MessageBox.Show("下游Tcp还没建立连接");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.LogError(ex.ToString());
                return false;
            }

        }


        public async Task<string> D_Tcp_SemdMsg(string message)
        {
            if (d_tcpstream != null)
            {
                byte[] msg = Encoding.ASCII.GetBytes(message);

                // 清空旧响应（关键）
                d_tcpResponse = string.Empty;

                //tcpstream.Write(msg, 0, msg.Length);
                await d_tcpstream.WriteAsync(msg, 0, msg.Length);
                d_tcpstream.Flush();

                var sw = new Stopwatch();
                sw.Start();
                while (string.IsNullOrEmpty(d_tcpResponse) && sw.ElapsedMilliseconds < 5000)
                {
                    await Task.Delay(10);
                }
                sw.Stop();

                if (string.IsNullOrEmpty(d_tcpResponse))
                {
                    LogService.Instance.LogError("等待响应超时");

                }
                return d_tcpResponse.Trim(); // 返回响应（去掉空格或换行）
            }
            else
            {
                return "";
            }
        }


        public async Task<string> D_ReadFormPLC(string readCommand)
        {
            try
            {
                // 发送指令并等待响应
                string response = await Instance.D_Tcp_SemdMsg(readCommand);

                // 判断是否是有效数据（不是 OK）
                if (response.Equals("OK", StringComparison.OrdinalIgnoreCase))
                {
                    MessageBox.Show("收到 'OK'，可能是上一次写入下游机台基恩士PLC的响应，请稍后再试。");
                    return "";
                }

                // 正常显示读取结果

                return response;

            }
            catch (TimeoutException)
            {
                LogService.Instance.LogError("读取超时，未收到下游机台基恩士PLC响应。");
                return "超时";
            }
            catch (Exception ex)
            {
                LogService.Instance.LogError("读取下游机台基恩士PLC失败: " + ex.Message);
                return "错误: " + ex.Message;
            }
        }

        public void D_ListenTcpMsg()
        {
            if (d_istcpListen)
            {
                MessageBox.Show("监听下游机台任务已在运行");
            }
            {
                Task.Factory.StartNew(() =>
                {
                    d_istcpListen = true;
                    byte[] buffer = new byte[1024];
                    while (d_istcpListen)
                    {
                        if (d_tcpstream.DataAvailable)
                        {
                            Array.Clear(buffer, 0, buffer.Length);
                            int bytelength = d_tcpstream.Read(buffer, 0, buffer.Length);
                            if (bytelength > 0)
                            {
                                d_tcpResponse = string.Empty;
                                d_tcpResponse = Encoding.ASCII.GetString(buffer, 0, bytelength);
                                string clean = d_tcpResponse.Trim();

                                // 忽略空响应或纯回车
                                if (!string.IsNullOrWhiteSpace(clean) && !clean.Equals("OK", StringComparison.OrdinalIgnoreCase))
                                {
                                    d_tcpResponse = clean; // 只有有效读数才赋值
                                }
                                else if (clean.Equals("OK", StringComparison.OrdinalIgnoreCase))
                                {
                                    // 可选：记录日志，但不覆盖 tcpResponse
                                    // tcpResponse 不更新，避免干扰读取
                                }
                            }
                        }
                        Thread.Sleep(10);
                    }
                    LogService.Instance.LogWarning("断开下游机台的监听");
                    d_istcpListen = false;
                });
            }
        }







































    }
}
